import Vue from 'vue'
import VueRouter from 'vue-router'
import { getItem } from '@/utils/author.js'
import nProgress from 'nprogress'
import 'nprogress/nprogress.css'
const Login = () => import('@/views/login/index.vue')
const Home = () => import('@/views/home/index.vue')
const Article = () => import('@/views/article/index.vue')
const Publish = () => import('@/views/publish/index.vue')
const Layout = () => import('@/views/layout/index.vue')

Vue.use(VueRouter)
const routes = [
  {
    path: '/login',
    component: Login
  },

  {
    path: '/',
    component: Layout,
    redirect: '/home',

    children: [
      {
        path: '/home',
        component: Home
      },
      {
        path: '/article',
        component: Article
      },
      {
        path: '/publish',
        component: Publish
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  nProgress.start()
  if (getItem()) {
    if (to.path.toLowerCase() === '/login') {
      next('/home')
    } else {
      next()
    }
  } else {
    if (to.path.toLowerCase() === '/login') {
      next()
    } else {
      next('/login')
    }
  }
})

router.afterEach((to, from) => {
  nProgress.done()
  // console.log(to, from)
})

const originalPush = VueRouter.prototype.push

VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}
export default router
